package com.dmjj.limit.controller;

import com.alibaba.fastjson.JSONArray;
import com.dmjj.common.base.BaseController;
import com.dmjj.common.base.LoginEntity;
import com.dmjj.common.result.ResultEnum;
import com.dmjj.common.result.ResultObject;
import com.dmjj.common.util.ListCopyToVOUtil;
import com.dmjj.common.util.PaginationVOUtil;
import com.dmjj.common.vo.ResultVO;
import com.dmjj.limit.dto.RoleDTO;
import com.dmjj.limit.dto.RoleLimitDTO;
import com.dmjj.limit.service.RoleLimitService;
import com.dmjj.limit.service.RoleService;
import com.dmjj.limit.vo.RoleLimitSaveVO2;
import com.dmjj.limit.vo.RoleLimitVO;
import com.dmjj.limit.vo.RoleUpdateVO;
import com.dmjj.limit.vo.RoleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description 角色表实体类控制器
 * @Author zhangxue
 * @Date 2019-03-21 09:40:56
 */

@RestController
@Api(tags = "角色表实体类控制器")
@RequestMapping("role")
public class RoleController extends BaseController {

    private static final Log LOGGER = LogFactory.getLog(RoleController.class);

    @Autowired
    private RoleService service;
    @Autowired
    private ResultObject resultObject;
    @Autowired
    private RoleLimitService roleLimitService;

    /**
	 * 角色表实体类列表
     * @Author zhangxue
     * @Date 2019-03-21 09:40:56
	 * @Param
	 * @Return
	 */
    @ApiOperation(value = "角色表实体类列表", response = RoleVO.class)
    @PostMapping("list4Page")
    public ResultVO<Object> list4Page(
            RoleVO entity,
            @ApiParam(value = "当前页", required = true) @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页显示条数", required = true) @RequestParam(value = "pageSize", defaultValue = "15") Integer pageSize
    ){
        try {
            RoleDTO entityDTO = new RoleDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<RoleDTO> list = service.list4Page(entityDTO, pageNum, pageSize);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), PaginationVOUtil.getPaginationVO(list, RoleVO.class, pageNum));
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 角色表实体类列表（无分页）
     * @Author zhangxue
     * @Date 2019-03-21 09:40:56
     * @Param
     * @Return
     */
    @ApiOperation(value = "角色表实体类列表（无分页）", response = RoleVO.class)
    @PostMapping("listByCondition")
    public ResultVO<Object> listByCondition(RoleVO entity){
        try {
            RoleDTO entityDTO = new RoleDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<RoleDTO> list = service.listByCondition(entityDTO);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), ListCopyToVOUtil.getListToVO(list, RoleVO.class));
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 角色表实体类详细信息
     * @Author zhangxue
     * @Date 2019-03-21 09:40:56
     * @Param
     * @Return
     */
    @ApiOperation(value = "角色表实体类详细信息", response = RoleVO.class)
    @PostMapping("queryOneByPk")
    public ResultVO<Object> queryOneByPk(@ApiParam(value = "id",required = true) @RequestParam(value = "id") Long id){
        try {
            RoleDTO entityDTO = service.queryOneByPk(id);
            RoleVO entity = new RoleVO();
            BeanUtils.copyProperties(entityDTO, entity);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), entity);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 保存角色表实体类信息
     * @Author zhangxue
     * @Date 2019-03-21 09:40:56
     * @Param
     * @Return
     */
    @ApiOperation(value = "保存角色表实体类信息", response = ResultVO.class)
    @PostMapping("save")
    public ResultVO<Object> save(RoleVO entity) {
        try {
            RoleDTO entityDTO = new RoleDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            //保存角色信息
            if(service.save(entityDTO) > 0) {
                //            LoginEntity loginEntity = getUserInfo();
                String Rolelimitjson = entity.getRolelimitjson();
                //saveList是要存入数据库的数据
                List<RoleLimitDTO> saveList = new ArrayList<RoleLimitDTO>();
                //获取所有需要插入的资源Id和其父节点Id
                List<RoleLimitSaveVO2> ts = JSONArray.parseArray(Rolelimitjson,RoleLimitSaveVO2.class);
                for(int i=0;i<ts.size();i++){
                    RoleLimitVO tempRoleLim = new RoleLimitVO();
                    tempRoleLim.setLimitid(ts.get(i).getLimitid());
                    tempRoleLim.setLimparentid(ts.get(i).getLimparentid());
                    tempRoleLim.setRoleid(entityDTO.getId());
                    tempRoleLim.setCreatetime(new Date());
//                tempRoleLim.setCreatemanno(loginEntity.getUserid());
//                tempRoleLim.setCreatemanname(loginEntity.getName());
                    RoleLimitDTO entityDTO2 = new RoleLimitDTO();
                    BeanUtils.copyProperties(tempRoleLim, entityDTO2);
                    saveList.add(entityDTO2);
                }
                Integer i = roleLimitService.saveList(saveList);
                if(i > 0) {
                    return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
                }else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
                }
            }else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 修改角色表实体类信息
     * @Author zhangxue
     * @Date 2019-03-21 09:40:56
     * @Param
     * @Return
     */
    @ApiOperation(value = "修改角色表实体类信息", response = ResultVO.class)
    @PostMapping("update")
    public ResultVO<Object> update(RoleUpdateVO entity) {
        try {
            RoleDTO entityDTO = new RoleDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            //修改角色信息
            if(service.update(entityDTO) > 0) {
                //            LoginEntity loginEntity = getUserInfo();
                Integer roleId = Integer.valueOf(entityDTO.getId());
                if(roleLimitService.deleteByRoleId(roleId)>0){
                    String Rolelimitjson = entity.getRolelimitjson();
                    //saveList是要存入数据库的数据
                    List<RoleLimitDTO> saveList = new ArrayList<RoleLimitDTO>();
                    //获取所有需要插入的资源Id和其父节点Id
                    List<RoleLimitSaveVO2> ts = JSONArray.parseArray(Rolelimitjson,RoleLimitSaveVO2.class);
                    for(int i=0;i<ts.size();i++){
                        RoleLimitVO tempRoleLim = new RoleLimitVO();
                        tempRoleLim.setLimitid(ts.get(i).getLimitid());
                        tempRoleLim.setLimparentid(ts.get(i).getLimparentid());
                        tempRoleLim.setRoleid(entityDTO.getId());
                        tempRoleLim.setCreatetime(new Date());
//                tempRoleLim.setCreatemanno(loginEntity.getUserid());
//                tempRoleLim.setCreatemanname(loginEntity.getName());
                        RoleLimitDTO entityDTO2 = new RoleLimitDTO();
                        BeanUtils.copyProperties(tempRoleLim, entityDTO2);
                        saveList.add(entityDTO2);
                    }
                    Integer i = roleLimitService.saveList(saveList);
                    if(i > 0) {
                        return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
                    }else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
                    }
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
                }

            }else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 删除角色表实体类信息
     * @Author zhangxue
     * @Date 2019-03-21 09:40:56
     * @Param
     * @Return
     */
    @ApiOperation(value = "删除角色表实体类信息", response = ResultVO.class)
    @PostMapping("delete")
    public ResultVO<Object> delete(@ApiParam(value = "id",required = true) @RequestParam(value = "id") Long id){
        try {
            if(service.delete(id) > 0) {
                return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
            }else {
                return resultObject.success(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 获取用户角色权限与数据权限
     * @Author zhangxue
     * @Date 2019-03-21 09:40:56
     * @Param
     * @Return
     */
    @ApiOperation(value = "获取用户角色权限与数据权限", response = ResultVO.class)
    @PostMapping("queryUserLimitByToken")
    public ResultVO<Object> queryUserLimitByToken(LoginEntity loginEntity){
        try {
            Map<String,Object> LimMap = service.queryUserLimitByToken(loginEntity);
            if(LimMap!=null) {
                return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),LimMap);
            }else {
                return resultObject.success(ResultEnum.FAIL.getCode(), "该用户未授权");
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

}